package net.ge.mosq.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.jsp.JspWriter;

import net.ge.mosq.jdo.entity.AccountItem;
import net.ge.mosq.jdo.factory.PMF;
import net.ge.mosq.service.ServiceFactory;

public class JspUtility {

	public static List<AccountItem> getAllAccounts(JspWriter out, String email)
			throws IOException {
		
		//ServiceFactory.getAccountService().getAllAccountWithTransInfo(null);
		PersistenceManager pm = PMF.get().getPersistenceManager();

		String sql = "select from " + AccountItem.class.getName()
				+ " where email == emailParam parameters String emailParam ";
//		q.setFilter("email == emailParam");
//		q.declareParameters("String emailParam");
		List<AccountItem> accountItems = (List<AccountItem>) pm.newQuery(sql).execute(email);
		int count = accountItems.size();
		List<AccountItem> allItems = new ArrayList<AccountItem>();
		int i = 1;
		for (AccountItem accountItem : accountItems) {
			System.out.println(i++ + "out+++: " + accountItem.getName());
//			if (accountItem.getParentKey() == null) {
//				allItems.add(accountItem);
//				deepSearchAccount(accountItems, accountItem);
//			}
		}
		List<AccountItem> result = new ArrayList<AccountItem>();
//		for (AccountItem accountItem : allItems) {
//			getAllAccountWithLevel(result, accountItem, 0);
//		}
		return result;
	}

	private static void deepSearchAccount(List<AccountItem> source,
			AccountItem parent) {
		for (AccountItem entity : source) {
			if (parent.getId() == entity.getParentId()) {
				if (parent.getChildenList() == null) {
					parent.setChildenList(new ArrayList<AccountItem>());
					parent.getChildenList().add(entity);
				} else {
					parent.getChildenList().add(entity);
				}
				deepSearchAccount(source, entity);
			}
		}
	}
	
	private static void getAllAccountWithLevel(List<AccountItem> result, AccountItem accItem, int level) {
		result.add(accItem);
		accItem.setLevel(level);
		
		if (accItem.getChildenList() != null && !accItem.getChildenList().isEmpty()) {
			for (AccountItem accountItem : accItem.getChildenList()) {
				getAllAccountWithLevel(result, accountItem, level + 1);
			}
		}
	}
	
	public static void main(String[] args) {
	}
}